<template>
  <div class="main">
    <input
      type="text"
      placeholder="输入用户名"
      class="input"
      @input="handleInputChange"
    />
    <p class="tips" v-show="!isShow">用户名只能修改一次（5-24字符之间）</p>
    <p class="length" v-show="isShow">用户名长度在5到24位之间</p>
    <div class="edit" :class="{ active: !isShow }" @click="handleEditName">
      确认修改
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isShow: false,
      newName: "",
      num: 0, //用于控制用户名只能修改一次
    };
  },
  methods: {
    handleInputChange(e) {
      if (
        e.target.value.trim().length < 5 ||
        e.target.value.trim().length > 24
      ) {
        this.isShow = true;
      } else {
        this.isShow = false;
        this.newName = e.target.value.trim();
      }
    },
    handleEditName() {
      if (this.newName.length > 5 && this.newName.length < 24 && this.newName) {
        if (++this.num === 1) {
          this.$store.commit("editUserInfoName", this.newName, this.num);
          this.$router.go(-1);
        } else {
          this.$toast.handleTipsText("用户名只能修改一次");
        }
      } else {
        this.$toast.handleTipsText("用户名不规范");
      }
    },
  },
};
</script>
<style lang="less" scoped>
.main {
  padding: 10px;
  .input {
    width: 100%;
    padding: 8px 3px;
    border: 2px solid #e7e7e7;
    background-color: #f2f2f2;
  }
  .tips,
  .length {
    margin: 10px 0 20px 0;
    font-size: 12px;
    color: #979997;
  }
  .length {
    color: #ea3106;
  }
  .edit {
    text-align: center;
    padding: 10px 0;
    background-color: #3199e8;
    color: #8cc6f2;
    transition: all 0.3s ease;
  }
  .active {
    color: #fff;
  }
}
</style>